#include "StateRequest.h"
#include "scImpl.h"

#define FCT "StateRequest::StateRequest"
StateRequest::StateRequest(unsigned long transId) :
	stConnect(-1), stSend(-1), stRecHead(-1), stRecBody(-1), stSuccess(-1), stFailed(-1), stTeardown(-1),
	transSucSuc(-1), transBodySuc(-1), id(transId)
{
	connect(this, SIGNAL(stateChangeSig(int)), this, SLOT(notifySl()));
	stConnect	=addState("CONNECT");
	stSend		=addState("SEND");
	stRecHead	=addState("REC_HEAD");
	stRecBody	=addState("REC_BODY");
	stSuccess	=addState("SUCCESS");
	stFailed	=addState("FAILED");
	// CONNECT out
	addTransition(stConnect, stSend);
	addTransition(stConnect, stFailed);
	// SEND out
	// no self-transition!
	addTransition(stSend, stRecHead);
	addTransition(stSend, stFailed);
	// REC_HEAD out
	// no self-transition!
	addTransition(stRecHead, stRecBody);
	addTransition(stRecHead, stFailed);
	// REC_BODY out
	// no self-transition!
	transBodySuc=addTransition(stRecBody, stSuccess);
	addTransition(stRecBody, stFailed);
	// SUCCESS out
	transSucSuc=addTransition(stSuccess, stSuccess); // for get/post requests during finish
	addTransition(stSuccess, stTeardown);
	// FAILED out
	addTransition(stFailed, stTeardown);
	// TEARDOWN out
	// no self-transition, final state
}

#undef FCT
#define FCT "StateRequest::~StateRequest"
StateRequest::~StateRequest()
{
}

#undef FCT
#define FCT "StateRequest::conditionalTransition"
int StateRequest::conditionalTransition(int targetState)
{
	int trans(tryTransition(targetState));
	if(trans<0)
		trans=makeTransition(stFailed);
	return trans;
}

/*
#undef FCT
#define FCT "StateRequest::finishedTransition"
int StateRequest::finishedTransition(bool headerOnly)
{
	int trans(testTransition(stSuccess));
	if(trans<0)
		trans=makeTransition(stFailed);
	else if( (headerOnly && trans==transBodySuc) || (!headerOnly && trans==transSucSuc))
		trans=makeTransition(stSuccess);
	else
		trans=makeTransition(stFailed);
	return trans;
}
*/

#undef FCT
#define FCT "StateRequest::notifySl"
void StateRequest::notifySl()
{
	if(state==stSuccess)
		emit stateSuccessSig(id);
	else if(state==stFailed)
		emit stateFailedSig(id);
}
